<template>
  <div class="adoption-cases-page">
    <!-- 背景图片 -->
    <div class="page_bg" :style="`background: url(${require('@/assets/images/indb.jpg')}) center top no-repeat;`"></div>
    
    <!-- 主要内容 -->
    <div class="container">
      <div class="row">
        <!-- 右侧主内容区域 -->
        <div class="col-xs-12 col-sm-8 col-md-9" style="float:right">
          <div class="list_box">
            <h2 class="left_h2">领养案例</h2>
            <div class="product_list product_list2 row">
              <!-- 领养案例卡片 -->
              <div 
                v-for="adoptionCase in paginatedCases" 
                :key="adoptionCase.id"
                class="col-sm-4 col-md-4 col-mm-6 product_img"
              >
                <router-link :to="`/adoption-cases/${adoptionCase.id}`">
                  <img 
                    :src="adoptionCase.image" 
                    class="img-thumbnail" 
                    :alt="adoptionCase.name"
                    @error="handleImageError"
                  >
                </router-link>
                <p class="product_title">
                  <router-link 
                    :to="`/adoption-cases/${adoptionCase.id}`" 
                    :title="adoptionCase.name"
                  >
                    {{ adoptionCase.name }}
                  </router-link>
                </p>
              </div>
              
              <!-- 分页 -->
              <div class="col-12" v-if="totalPages > 1">
                <div class="pagebar">
                  <div class="pagination">
                    <a 
                      class="page-item page-link st" 
                      @click="goToPage(currentPage - 1)"
                      :class="{ disabled: currentPage === 1 }"
                      href="javascript:;" 
                      title="上一页"
                    >
                      &lt;&lt;
                    </a>
                    <a 
                      v-for="page in visiblePages" 
                      :key="page"
                      @click="goToPage(page)"
                      :class="['page-num', { 'page-num-current': page === currentPage }]"
                      href="javascript:;"
                    >
                      {{ page }}
                    </a>
                    <a class="page-item page-link" href="javascript:;" :title="`当前页/总页数`">
                      {{ currentPage }}/{{ totalPages }}
                    </a>
                    <a 
                      class="page-item page-link st" 
                      @click="goToPage(currentPage + 1)"
                      :class="{ disabled: currentPage === totalPages }"
                      href="javascript:;" 
                      title="下一页"
                    >
                      &gt;&gt;
                    </a>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 左侧边栏 -->
        <div class="col-xs-12 col-sm-4 col-md-3">
          <!-- 导航菜单 -->
          <div class="left_nav" id="categories">
            <h2 class="left_h2">领养案例</h2>
            <ul class="left_nav_ul" id="firstpane">
              <!-- 可以在这里添加子分类 -->
            </ul>
          </div>
          
          <!-- 搜索框 -->
          <form @submit.prevent="performSearch">
            <div class="input-group search_group">
              <input 
                type="text" 
                v-model="searchKeyword"
                class="form-control input-sm" 
                placeholder="信息查询"
              >
              <span class="input-group-btn">
                <button @click="performSearch" class="btn btn-sm mysearch_btn" type="button">
                  搜 索
                </button>
              </span>
            </div>
          </form>
          
          <!-- 养宠知识 -->
          <div class="left_news">
            <h2 class="left_h2">养宠知识</h2>
            <ul>
              <li v-for="knowledge in knowledgeList" :key="knowledge.id">
                <router-link :to="`/pet-column/knowledge/${knowledge.id}`" :title="knowledge.title">
                  {{ knowledge.title }}
                </router-link>
                <span class="news_time">{{ formatDate(knowledge.date) }}</span>
              </li>
            </ul>
          </div>
          
          <!-- 联系我们 -->
          <div class="left_contact">
            <h2 class="left_h2" style="margin-bottom:20px;">联系我们</h2>
            <p>联系人：{{ contactInfo.name }}</p>
            <p>手机：{{ contactInfo.phone }}</p>
            <p>电话：{{ contactInfo.tel }}</p>
            <p>邮箱：{{ contactInfo.email }}</p>
            <p>地址：{{ contactInfo.address }}</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ApiService } from '@/services/api'

export default {
  name: 'AdoptionCases',
  data() {
    return {
      searchKeyword: '',
      currentPage: 1,
      pageSize: 6, // 每页显示6个案例
      filteredCases: [], // 搜索过滤后的案例
      loading: false,
      error: null,
      totalCases: 0,
      totalPages: 0,
      adoptionCases: [
        {
          id: 1,
          name: 'coco的领养案例',
          image: require('@/assets/images/20230417/1681740318301726.jpg'),
          status: '已成功领养',
          adopter: '张女士',
          adoptDate: '2023-04-17',
          description: 'coco是一只温顺可爱的小狗，现在已经找到了温暖的家庭。'
        },
        {
          id: 2,
          name: '小雪',
          image: require('@/assets/images/20230424/1682332942505948.jpg'),
          status: '已成功领养',
          adopter: '李先生',
          adoptDate: '2023-04-24',
          description: '小雪是一只聪明的白色小狗，很快就适应了新家庭。'
        },
        {
          id: 3,
          name: '阿呆',
          image: require('@/assets/images/20230423/1682257069276480.jpg'),
          status: '已成功领养',
          adopter: '王女士',
          adoptDate: '2023-04-23',
          description: '阿呆虽然叫这个名字，但其实很聪明，现在过得很幸福。'
        },
        {
          id: 4,
          name: '米奇',
          image: require('@/assets/images/20230423/1682257047659615.jpg'),
          status: '已成功领养',
          adopter: '陈先生',
          adoptDate: '2023-04-23',
          description: '米奇是一只活泼的小狗，给新家庭带来了很多欢乐。'
        },
        {
          id: 5,
          name: '小花',
          image: require('@/assets/images/20230423/1682256877856387.jpg'),
          status: '已成功领养',
          adopter: '赵女士',
          adoptDate: '2023-04-22',
          description: '小花是一只美丽的猫咪，现在生活在一个爱猫的家庭里。'
        },
        {
          id: 6,
          name: '大黄',
          image: require('@/assets/images/20230423/1682256826549167.jpg'),
          status: '已成功领养',
          adopter: '孙先生',
          adoptDate: '2023-04-21',
          description: '大黄是一只忠诚的狗狗，现在是家庭的守护神。'
        },
        {
          id: 7,
          name: '小白',
          image: require('@/assets/images/20230423/1682256770898273.jpg'),
          status: '已成功领养',
          adopter: '周女士',
          adoptDate: '2023-04-20',
          description: '小白是一只纯白色的猫咪，现在是家里的小公主。'
        },
        {
          id: 8,
          name: '球球',
          image: require('@/assets/images/20230423/1682256728449555.jpg'),
          status: '已成功领养',
          adopter: '吴先生',
          adoptDate: '2023-04-19',
          description: '球球喜欢玩球，现在每天都能和新主人一起玩耍。'
        }
      ],
      knowledgeList: [
        {
          id: 1,
          title: '猫为什么会炸毛',
          date: '2023-04-22'
        },
        {
          id: 2,
          title: '如何训练小狗上厕所',
          date: '2023-04-21'
        },
        {
          id: 3,
          title: '宠物疫苗接种指南',
          date: '2023-04-20'
        }
      ],
      contactInfo: {
        name: '贫僧',
        phone: '暂无',
        tel: '暂无',
        email: '暂无',
        address: '暂无'
      }
    }
  },
  computed: {
    // 分页后的案例
    paginatedCases() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      return this.filteredCases.slice(start, end)
    },
    // 可见的页码
    visiblePages() {
      const pages = []
      const maxVisiblePages = 5
      let start = Math.max(1, this.currentPage - Math.floor(maxVisiblePages / 2))
      let end = Math.min(this.totalPages, start + maxVisiblePages - 1)
      
      if (end - start < maxVisiblePages - 1) {
        start = Math.max(1, end - maxVisiblePages + 1)
      }
      
      for (let i = start; i <= end; i++) {
        pages.push(i)
      }
      return pages
    }
  },
  async mounted() {
    // 从URL参数获取搜索关键词和页码
    this.searchKeyword = this.$route.query.search || ''
    this.currentPage = parseInt(this.$route.query.page) || 1
    
    // 初始化：从API获取数据
    await this.fetchCases()
  },
  methods: {
    // 从API获取案例数据
    async fetchCases() {
      this.loading = true
      this.error = null
      
      try {
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize
        }
        
        if (this.searchKeyword.trim()) {
          params.search = this.searchKeyword.trim()
        }
        
        console.log('🚀 API请求参数:', params)
        const response = await ApiService.getAdoptionCases(params)
        console.log('✅ API响应:', response)
        
        if (response.success) {
          this.adoptionCases = response.data
          this.filteredCases = response.data
          this.totalCases = response.total
          this.totalPages = response.totalPages
        } else {
          this.error = response.message || '获取数据失败'
        }
      } catch (error) {
        console.error('❌ API请求失败:', error)
        this.error = '网络错误，请稍后再试'
      } finally {
        this.loading = false
      }
    },

    // 跳转到指定页面
    async goToPage(page) {
      if (page >= 1 && page <= this.totalPages && page !== this.currentPage) {
        this.currentPage = page
        
        // 更新URL参数
        const query = { ...this.$route.query, page }
        if (page === 1) delete query.page
        this.$router.push({ path: this.$route.path, query })
        
        // 重新获取数据
        await this.fetchCases()
        
        // 滚动到顶部
        window.scrollTo({ top: 0, behavior: 'smooth' })
      }
    },
    // 执行搜索
    async performSearch() {
      this.searchKeyword = this.searchKeyword.trim()
      this.currentPage = 1
      
      // 更新URL参数
      const query = this.searchKeyword ? { search: this.searchKeyword } : {}
      this.$router.push({ path: this.$route.path, query })
      
      // 重新获取数据
      await this.fetchCases()
    },
    // 处理图片加载失败
    handleImageError(event) {
      event.target.style.display = 'none'
      const parent = event.target.parentElement
      if (parent && !parent.querySelector('.pet-error-placeholder')) {
        const placeholder = document.createElement('div')
        placeholder.className = 'pet-error-placeholder'
        placeholder.style.cssText = 'width:100%;height:200px;background:#04A07B;color:white;display:flex;align-items:center;justify-content:center;border-radius:4px;font-size:14px;'
        placeholder.textContent = '🐾 图片加载失败'
        parent.appendChild(placeholder)
      }
    },
    // 格式化日期
    formatDate(dateString) {
      const date = new Date(dateString)
      return `${String(date.getMonth() + 1).padStart(2, '0')}/${String(date.getDate()).padStart(2, '0')}`
    }
  }
}
</script>

<style scoped>
.adoption-cases-page {
  padding-top: 0; /* 使用全局body padding-top */
}

.page_bg {
  height: 200px;
  background-size: cover !important;
  background-position: center !important;
  margin-bottom: 30px;
}

.list_box {
  background: white;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.left_h2 {
  color: #04A07B;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 2px solid #04A07B;
}

.product_list {
  margin: 0 -10px;
}

.product_img {
  padding: 0 10px;
  margin-bottom: 20px;
}

.product_img img {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 4px;
  transition: transform 0.3s ease;
}

.product_img img:hover {
  transform: scale(1.05);
}

.product_title {
  margin-top: 10px;
  text-align: center;
}

.product_title a {
  color: #333;
  text-decoration: none;
  font-weight: 500;
}

.product_title a:hover {
  color: #04A07B;
}

/* 侧边栏样式 */
.left_nav, .left_news, .left_contact {
  background: white;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.search_group {
  margin-bottom: 20px;
}

.mysearch_btn {
  background: #04A07B;
  color: white;
  border: none;
}

.mysearch_btn:hover {
  background: #038066;
}

.left_news ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.left_news li {
  padding: 8px 0;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left_news li:last-child {
  border-bottom: none;
}

.left_news a {
  color: #333;
  text-decoration: none;
  flex: 1;
  margin-right: 10px;
}

.left_news a:hover {
  color: #04A07B;
}

.news_time {
  color: #999;
  font-size: 12px;
}

.left_contact p {
  margin-bottom: 8px;
  color: #666;
}

/* 分页样式 */
.pagebar {
  text-align: center;
  margin-top: 30px;
}

.pagination {
  display: inline-flex;
  gap: 5px;
}

.page-item, .page-num {
  display: inline-block;
  padding: 8px 12px;
  margin: 0 2px;
  background: white;
  border: 1px solid #ddd;
  color: #333;
  text-decoration: none;
  border-radius: 4px;
  cursor: pointer;
}

.page-item:hover, .page-num:hover {
  background: #04A07B;
  color: white;
  border-color: #04A07B;
}

.page-num-current {
  background: #04A07B !important;
  color: white !important;
  border-color: #04A07B !important;
}

.page-item.disabled {
  background: #f8f9fa;
  color: #6c757d;
  cursor: not-allowed;
  pointer-events: none;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .col-xs-12.col-sm-8.col-md-9 {
    float: none !important;
    order: 2;
  }
  
  .col-xs-12.col-sm-4.col-md-3 {
    order: 1;
    margin-bottom: 20px;
  }
  
  .adoption-cases-page {
    padding-top: 0; /* 使用全局body padding-top */
  }
}
</style>